/**
 *    Copyright 2012 Geensoft S.A.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 **/
package ar.com.greensoft.neosystem.services.impl;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.logging.Logger;

import javax.ejb.Stateless;
import javax.inject.Inject;

import org.apache.commons.codec.binary.Base64;

import ar.com.greensoft.neosystem.services.Encoded;
import ar.com.greensoft.neosystem.services.PasswordEncoder;
import ar.com.greensoft.neosystem.services.Encoded.Algoithm;

/**
 * 
 * @author Jorge E. Villaverde
 * @since 1.0.0
 * @version 1.0.0
 */
@Stateless
@Encoded(Algoithm.BASE64)
public class MD5Base64PasswordEncoder implements PasswordEncoder {
	@Inject
	private Logger logger;

	@Override
	public String encodePassword(String rawPass) {
		return getMD5_Base64(rawPass);
	}

	@Override
	public boolean isPasswordValid(String encPass, String rawPass) {
		logger.info("Encodign password: " + rawPass);
		return encPass.equals(getMD5_Base64(rawPass));
	}

	public synchronized String getMD5_Base64(String input) {
		MessageDigest digest;
		try {
			digest = MessageDigest.getInstance("MD5");
			if (digest == null)
				return input;

			// now everything is ok, go ahead
			try {
				digest.update(input.getBytes("UTF-8"));
			} catch (java.io.UnsupportedEncodingException ex) {
			}
			byte[] rawData = digest.digest();
			byte[] encoded = Base64.encodeBase64(rawData);
			
			logger.info("MD5 password: " + new String(rawData));
			logger.info("MD5 Base64 password: " + new String(encoded));
			
			String retValue = new String(encoded);
			return retValue;
		} catch (NoSuchAlgorithmException e) {
			logger.severe(e.getMessage());
		}
		return null;
	}
}
